#!/bin/bash
set -euo pipefail
###
# 优化版系统初始化脚本
# 改进点：兼容云环境、增强错误处理、优化内核参数
# 最后更新：2024-08-30
# 执行方式：curl -sL http://wuyou.run/scripts/system/init/all.sh | bash -s [hostname]
###

# ----------- 日志配置 ----------- #
LOG_FILE="/var/log/system_init_$(date +%Y%m%d%H%M).log"
exec > >(tee -a "${LOG_FILE}") 2>&1

# ----------- 颜色输出函数 ----------- #
function print_msg() {
    local RED='\e[1;31m'
    local GREEN='\e[1;32m'
    local YELLOW='\e[1;33m'
    local BLUE='\e[1;34m'
    local RESET='\e[0m'

    case "$1" in
        "error"|"red")    echo -e "${RED}$2${RESET}" ;;
        "warn"|"yellow")  echo -e "${YELLOW}$2${RESET}" ;;
        "info"|"blue")     echo -e "${BLUE}$2${RESET}" ;;
        "success"|"green") echo -e "${GREEN}$2${RESET}" ;;
        *) echo "$2" ;;
    esac
}

# ----------- 预检检查 ----------- #
pre_check() {
    if [ $(id -u) -ne 0 ]; then
        print_msg error "必须使用root权限执行此脚本"
        exit 1
    fi

    # 检测云环境
    if [ -f /etc/cloud/cloud.cfg ]; then
        CLOUD_ENV=true
        print_msg info "检测到云平台环境"
    else
        CLOUD_ENV=false
    fi
}

# ----------- 通用函数 ----------- #
set_swap() {
    print_msg info "处理Swap分区..."
    if swapon --show | grep -q '/'; then
        swapoff -a
        # 备份fstab文件
        cp /etc/fstab /etc/fstab.bak_$(date +%Y%m%d)
        sed -i '/swap/d' /etc/fstab
    else
        print_msg warn "未检测到活跃的Swap分区，跳过处理"
    fi
}

set_timezone() {
    print_msg info "配置时区..."
    timedatectl set-timezone Asia/Shanghai
    timedatectl | grep "Time zone"
}



optimize_kernel() {
    print_msg info "优化内核参数..."
    local sysctl_conf="/etc/sysctl.conf"
    
    # 备份原有配置
    cp "$sysctl_conf" "${sysctl_conf}.bak_$(date +%Y%m%d)"

    # 核心参数（兼容云环境）
    cat >> "$sysctl_conf" <<EOF
# Custom Kernel Parameters
fs.file-max = 1048576
fs.inotify.max_user_instances = 8192
fs.inotify.max_user_watches = 524288

net.ipv4.tcp_max_syn_backlog = 8192
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30
net.core.somaxconn = 8192
net.core.netdev_max_backlog = 16384

# 容器化优化
vm.swappiness = 10
vm.overcommit_memory = 1
kernel.panic = 10
EOF

    # K8s相关参数（检测到桥接模块时设置）
    if lsmod | grep -q bridge; then
        cat > /etc/sysctl.d/k8s.conf <<EOF
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
EOF
    fi

    sysctl --system >/dev/null
}

# ----------- 发行版特定函数 ----------- #
init_centos() {
    print_msg info "执行CentOS初始化..."
    
    # 基础软件
    yum install -q -y epel-release
    yum install -q -y \
        telnet wget curl sysstat dstat iotop iftop \
        lsof nmap nc bind-utils jq
    
    # 安全加固
    setenforce 0
    sed -i 's/^SELINUX=.*/SELINUX=disabled/g' /etc/selinux/config
    
    systemctl stop firewalld
    systemctl disable firewalld
}

init_ubuntu() {
    print_msg info "执行Ubuntu初始化..."
    
    # 基础软件
    apt-get update -qq
    apt-get install -y -qq \
        telnet wget curl sysstat dstat iotop iftop \
        lsof nmap netcat bind9-utils jq
    
    # 安全配置
    ufw disable
}

# ----------- 主流程 ----------- #
main() {
    pre_check
    
    # 设置主机名（支持传参）
    local hostname=${1:-"default-host"}
    hostnamectl set-hostname "$hostname"
    sed -i "/127.0.0.1/c 127.0.0.1   localhost $hostname" /etc/hosts

    # 通用初始化
    set_swap
    set_timezone
    optimize_kernel

    # 发行版特定初始化
    case $(grep '^ID=' /etc/os-release | cut -d= -f2) in
        "centos") init_centos ;;
        "ubuntu") init_ubuntu ;;
        *) print_msg warn "不支持的发行版，跳过特定初始化" ;;
    esac

    # 云环境特殊处理
    if $CLOUD_ENV; then
        print_msg info "执行云环境优化..."
        # 示例：禁用cloud-init
        systemctl stop cloud-init
        systemctl disable cloud-init
    fi

    print_msg success "初始化完成！详细日志见：${LOG_FILE}"
}

# ----------- 执行主函数 ----------- #
main "$@"